package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatMessageMediaDTO;
import com.zenithmind.chat.pojo.vo.ChatMessageMediaVO;
import com.zenithmind.chat.service.ChatMessageMediaService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 消息媒体文件控制器 - 遵循单一职责原则
 * 只负责消息媒体文件的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/message-media")
@RequiredArgsConstructor
@Validated
@Tag(name = "消息媒体文件管理", description = "消息媒体文件相关接口")
public class ChatMessageMediaController {

    private final ChatMessageMediaService chatMessageMediaService;

    @PostMapping("/upload")
    @Operation(summary = "上传媒体文件", description = "上传消息媒体文件")
    public Result<String> uploadMedia(@Valid @RequestBody ChatMessageMediaDTO dto) {
        String userId = UserContext.getUserId();
        String mediaId = chatMessageMediaService.uploadMedia(dto, userId);
        return Result.success(mediaId);
    }

    @PostMapping("/batch-upload")
    @Operation(summary = "批量上传媒体文件", description = "批量上传多个媒体文件")
    public Result<List<String>> batchUploadMedia(@RequestBody @NotEmpty List<ChatMessageMediaDTO> dtoList) {
        String userId = UserContext.getUserId();
        List<String> mediaIds = chatMessageMediaService.batchUploadMedia(dtoList, userId);
        return Result.success(mediaIds);
    }

    @GetMapping("/message/{messageId}")
    @Operation(summary = "查询消息媒体文件", description = "根据消息ID查询媒体文件列表")
    public Result<List<ChatMessageMediaVO>> getMediaByMessageId(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        List<ChatMessageMediaVO> mediaList = chatMessageMediaService.getMediaByMessageId(messageId);
        return Result.success(mediaList);
    }

    @GetMapping("/{mediaId}")
    @Operation(summary = "查询媒体文件详情", description = "根据媒体文件ID查询详细信息")
    public Result<ChatMessageMediaVO> getMediaById(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId) {
        String userId = UserContext.getUserId();
        ChatMessageMediaVO media = chatMessageMediaService.getMediaById(mediaId, userId);
        return Result.success(media);
    }

    @PutMapping("/{mediaId}")
    @Operation(summary = "更新媒体文件信息", description = "更新媒体文件的信息")
    public Result<Boolean> updateMedia(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId,
            @Valid @RequestBody ChatMessageMediaDTO dto) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.updateMedia(mediaId, dto, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{mediaId}")
    @Operation(summary = "删除媒体文件", description = "删除指定的媒体文件")
    public Result<Boolean> deleteMedia(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.deleteMedia(mediaId, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除媒体文件", description = "批量删除多个媒体文件")
    public Result<Boolean> batchDeleteMedia(@RequestBody @NotEmpty List<String> mediaIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.batchDeleteMedia(mediaIds, userId);
        return Result.success(result);
    }

    @DeleteMapping("/message/{messageId}")
    @Operation(summary = "删除消息的所有媒体文件", description = "删除指定消息的所有媒体文件")
    public Result<Boolean> deleteMediaByMessageId(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.deleteMediaByMessageId(messageId, userId);
        return Result.success(result);
    }

    @GetMapping("/user/list")
    @Operation(summary = "查询用户媒体文件", description = "查询用户上传的媒体文件列表")
    public Result<List<ChatMessageMediaVO>> getUserMediaList(
            @Parameter(description = "媒体类型") @RequestParam(required = false) String mediaType,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        List<ChatMessageMediaVO> mediaList = chatMessageMediaService.getUserMediaList(userId, mediaType, pageNum, pageSize);
        return Result.success(mediaList);
    }

    @GetMapping("/group/{groupId}/list")
    @Operation(summary = "查询群组媒体文件", description = "查询群组的媒体文件列表")
    public Result<List<ChatMessageMediaVO>> getGroupMediaList(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "媒体类型") @RequestParam(required = false) String mediaType,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        List<ChatMessageMediaVO> mediaList = chatMessageMediaService.getGroupMediaList(groupId, mediaType, pageNum, pageSize);
        return Result.success(mediaList);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索媒体文件", description = "根据关键词搜索媒体文件")
    public Result<List<ChatMessageMediaVO>> searchMedia(
            @Parameter(description = "关键词") @RequestParam @NotBlank String keyword,
            @Parameter(description = "媒体类型") @RequestParam(required = false) String mediaType,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        List<ChatMessageMediaVO> mediaList = chatMessageMediaService.searchMedia(keyword, mediaType, userId, pageNum, pageSize);
        return Result.success(mediaList);
    }

    @GetMapping("/{mediaId}/download-url")
    @Operation(summary = "获取下载链接", description = "获取媒体文件的下载链接")
    public Result<String> getDownloadUrl(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId) {
        String userId = UserContext.getUserId();
        String downloadUrl = chatMessageMediaService.getDownloadUrl(mediaId, userId);
        return Result.success(downloadUrl);
    }

    @GetMapping("/{mediaId}/preview-url")
    @Operation(summary = "获取预览链接", description = "获取媒体文件的预览链接")
    public Result<String> getPreviewUrl(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId) {
        String userId = UserContext.getUserId();
        String previewUrl = chatMessageMediaService.getPreviewUrl(mediaId, userId);
        return Result.success(previewUrl);
    }

    @GetMapping("/{mediaId}/check-access")
    @Operation(summary = "检查访问权限", description = "检查用户是否有权限访问媒体文件")
    public Result<Boolean> checkMediaAccess(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId) {
        String userId = UserContext.getUserId();
        Boolean hasAccess = chatMessageMediaService.checkMediaAccess(mediaId, userId);
        return Result.success(hasAccess);
    }

    @GetMapping("/user/statistics")
    @Operation(summary = "用户媒体统计", description = "获取用户媒体文件使用统计")
    public Result<Object> getUserMediaStatistics() {
        String userId = UserContext.getUserId();
        Object statistics = chatMessageMediaService.getUserMediaStatistics(userId);
        return Result.success(statistics);
    }

    @GetMapping("/group/{groupId}/statistics")
    @Operation(summary = "群组媒体统计", description = "获取群组媒体文件使用统计")
    public Result<Object> getGroupMediaStatistics(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId) {
        Object statistics = chatMessageMediaService.getGroupMediaStatistics(groupId);
        return Result.success(statistics);
    }

    @PostMapping("/cleanup-expired")
    @Operation(summary = "清理过期媒体文件", description = "清理过期的媒体文件")
    public Result<Integer> cleanupExpiredMedia(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "30") Integer retentionDays) {
        Integer cleanedCount = chatMessageMediaService.cleanupExpiredMedia(retentionDays);
        return Result.success(cleanedCount);
    }

    @PostMapping("/{mediaId}/compress")
    @Operation(summary = "压缩媒体文件", description = "压缩指定的媒体文件")
    public Result<Boolean> compressMedia(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId,
            @Parameter(description = "压缩质量") @RequestParam(defaultValue = "80") Integer quality) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.compressMedia(mediaId, quality, userId);
        return Result.success(result);
    }

    @PostMapping("/{mediaId}/thumbnail")
    @Operation(summary = "生成缩略图", description = "为媒体文件生成缩略图")
    public Result<String> generateThumbnail(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId,
            @Parameter(description = "宽度") @RequestParam(defaultValue = "200") Integer width,
            @Parameter(description = "高度") @RequestParam(defaultValue = "200") Integer height) {
        String userId = UserContext.getUserId();
        String thumbnailUrl = chatMessageMediaService.generateThumbnail(mediaId, width, height, userId);
        return Result.success(thumbnailUrl);
    }

    @PostMapping("/{mediaId}/convert")
    @Operation(summary = "转换媒体格式", description = "转换媒体文件格式")
    public Result<Boolean> convertMediaFormat(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId,
            @Parameter(description = "目标格式") @RequestParam @NotBlank String targetFormat) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.convertMediaFormat(mediaId, targetFormat, userId);
        return Result.success(result);
    }

    @PostMapping("/{sourceMediaId}/copy")
    @Operation(summary = "复制媒体文件", description = "复制媒体文件到其他消息")
    public Result<String> copyMedia(
            @Parameter(description = "源媒体文件ID") @PathVariable @NotBlank String sourceMediaId,
            @Parameter(description = "目标消息ID") @RequestParam @NotBlank String targetMessageId) {
        String userId = UserContext.getUserId();
        String newMediaId = chatMessageMediaService.copyMedia(sourceMediaId, targetMessageId, userId);
        return Result.success(newMediaId);
    }

    @PutMapping("/{mediaId}/move")
    @Operation(summary = "移动媒体文件", description = "移动媒体文件到其他消息")
    public Result<Boolean> moveMedia(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId,
            @Parameter(description = "目标消息ID") @RequestParam @NotBlank String targetMessageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.moveMedia(mediaId, targetMessageId, userId);
        return Result.success(result);
    }

    @PutMapping("/{mediaId}/access")
    @Operation(summary = "设置访问权限", description = "设置媒体文件的访问权限")
    public Result<Boolean> setMediaAccess(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId,
            @Parameter(description = "访问级别") @RequestParam @NotBlank String accessLevel) {
        String userId = UserContext.getUserId();
        Boolean result = chatMessageMediaService.setMediaAccess(mediaId, accessLevel, userId);
        return Result.success(result);
    }

    @GetMapping("/{mediaId}/metadata")
    @Operation(summary = "获取媒体元数据", description = "获取媒体文件的元数据信息")
    public Result<Object> getMediaMetadata(
            @Parameter(description = "媒体文件ID") @PathVariable @NotBlank String mediaId) {
        String userId = UserContext.getUserId();
        Object metadata = chatMessageMediaService.getMediaMetadata(mediaId, userId);
        return Result.success(metadata);
    }
}
